import 'systemjs'
import { isHttp, hasVersion } from './utils'

interface Config {
  unpkg?: string
  tag?: string
  location: string
}

let systemConfig: Config

export const configFetchLib = (config: Partial<Config>) => {
  systemConfig = {
    unpkg: config.unpkg,
    tag: config.tag,
    location: config.location || 'dist/system/index.js'
  }
}

export const fetchLib = (url: string) => {
  const _importSystem = (url: string) => {
    return System.import(url)
  }
  //  判断url情况
  // 当为 https 或者 http时
  if (isHttp(url)) {
    return _importSystem(url)
  }
  // 判断是否有版本号
  const isVersion = hasVersion(url)
  if (isVersion) {
    return _importSystem(`${systemConfig.unpkg}/${url}/${systemConfig.location}`)
  }
  // 判断是否有tag
  if (systemConfig.tag) {
    return _importSystem(`${systemConfig.unpkg}/${url}@${systemConfig.tag}/${systemConfig.location}`)
  }
  return _importSystem(`${systemConfig.unpkg}/${url}/${systemConfig.location}`)
}
